package br.ufmg.ubicomp.droidguide.communication;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import br.ufmg.ubicomp.droidguide.utils.XmlElement;
import br.ufmg.ubicomp.droidguide.utils.XmlParseUtil;

public class AuthenticationCommunicationService extends CommunicationService{
	
	//public static final String BASE_URL = "http://droidguide.appspot.com/user/process?operation=";
	
//	public static void login(String email, String deviceName, String connectivity) throws Exception {
//		String url = BASE_URL + "login&";
//		
//		url = url + "email=" + email;
//		url = url + "&deviceName=" + deviceName;
//		url = url + "&connectivity=" + connectivity;
//		
//		/* Make request */
//		DefaultHttpClient client = new DefaultHttpClient();
//		HttpGet method = new HttpGet(url);		
//		HttpResponse response =  client.execute(method);
//		HttpEntity entity = response.getEntity();
//		InputStream inStream = entity.getContent();
//		
//		//TODO: Response?
//	}

	/**
	 * provides login service.
	 * @throws IOException 
	 */
	public Map<String, String> executeLogin(String user, String deviceName,
			String connectivity) throws IOException {
		// http://localhost:8080/user/process?operation=login&email=waldir.pires@gmail.com&device_name=DG002&connectivity=WLAN
		String operation = "user/process";
		String params = "operation=login&email=" + user + "@gmail.com&device_name="
				+ deviceName + "&connectivity=" + connectivity;
		String result = executeUrl(operation.concat(params));
		Map<String, String> objetos = new HashMap<String, String>();
		if (result != null) {
			// use the XML parser over the returned data
			Collection<XmlElement> elements = 
				XmlParseUtil.getXmlElementsFromServer(result);
			getObjectMaps(objetos, elements);
			// get the droidguideuser key fr future referente
			// goto the next steps: profile, etc.
		}
		return objetos;
	}
	
	private void getObjectMaps(Map<String, String> objetos,
			Collection<XmlElement> elements) {
		if (!elements.isEmpty())
		{
			for (XmlElement e: elements)
			{
				if (e.getName().equals("object"))
				{
					String kind = e.getAttributes().get("kind");
					String key = e.getAttributes().get("key");
					objetos.put(kind, key);
				}
			}
		}
	}
	
	/**
	 * executes logout
	 * @throws IOException 
	 */
	public void executeLogout(String dgKey) throws IOException {
		// http://localhost:8080/user/process?operation=logout&droidGuideUser_key=agpkcm9pZGd1aWRlchQLEg5Ecm9pZEd1aWRlVXNlchgjDA
		String operation = "user/process";
		String params = "operation=logout&droidGuideUser_key=" + dgKey;
		String result = executeUrl(operation.concat(params));
		if (result != null) {
			// use the XML parser over the returned data
			// get the droidguideuser key fr future referente
			// goto the next steps: profile, etc.
		}
	}
	
}
